import axios from 'axios'

const API_URL = 'http://localhost:8080/library'

class AuthService {
    login(credentials) {
        // 使用URLSearchParams构造表单数据
        const params = new URLSearchParams()
        params.append('username', credentials.username)
        params.append('password', credentials.password)

        return axios.post(`${API_URL}/login`, params, {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            withCredentials: true // 允许携带cookie
        }).then(response => {
            // 直接返回后端响应数据
            return response.data
        }).catch(error => {
            console.error('登录失败:', error)
            return {
                success: false,
                message: '登录失败，请稍后再试'
            }
        })
    }

    logout() {
        return axios.get(`${API_URL}/logout`, {
            withCredentials: true
        })
    }
}

export default new AuthService()